package com.chatplus.application.web.util;

import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.util.ObjectUtils;

/**
 * 获取客户端ip地址
 *
 * @author chj
 * @date 2022/4/13
 **/
public class IpUtil {

    static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(IpUtil.class);

    private IpUtil() {
    }

    public static final String UN_KNOWN = "unKnown";

    /**
     * 获取客户端真实ip
     *
     * @param request domain
     * @return String
     */
    public static String getRemoteIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (!ObjectUtils.isEmpty(ip) && !UN_KNOWN.equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (!ObjectUtils.isEmpty(ip) && !UN_KNOWN.equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }
}
